<?php
require APPPATH . '/libraries/PHP/ChuanglanSmsHelper/ChuanglanSmsApi.php';
require APPPATH . '/libraries/youzan/YZGetTokenClient.php';
require APPPATH . '/libraries/youzan/YZTokenClient.php';
/**
 * Created by PhpStorm.
 * User: dumbledore
 * Date: 2017/12/25
 * Time: 上午10:12
 */
class Msg extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('form_validation'); //加载表单验证类库
        $this->load->helper('json');
        $this->load->helper('common');
        $this->load->model('api_model');
        $this->load->model('msg_model');
        $this->load->library('session');
    }

    public function send_msg()
    {
        $client_id     = "18caa55a5c38ae75eb"; //应用的 client_id
        $client_secret = "5a85c9367c44323099993884fae0cedd"; //应用的 client_secret

        $json = file_get_contents('php://input');
        $data = json_decode($json, true);

        //获取手机号码
        $token          = new YZGetTokenClient($client_id, $client_secret);
        $type           = 'self';
        $keys['kdt_id'] = '40344672';
        $access_token   = $token->get_token($type, $keys);
        $token          = $access_token['access_token']; //请填入商家授权后获取的access_token
        $client         = new YZTokenClient($token);
        $method         = 'youzan.trade.get'; //要调用的api名称
        $api_version    = '4.0.0'; //要调用的api版本号
        $my_params      = [
            'tid' => $data['id'],
        ];
        $my_files = [
        ];
        $info = $client->post($method, $api_version, $my_params, $my_files);
        if (isset($info['response']['full_order_info']['buyer_info']['buyer_phone'])) {
            //$phone = $info['response']['full_order_info']['buyer_info']['buyer_phone'];
            $phone = $info['response']['full_order_info']['address_info']['receiver_tel'];
        } else {
            $phone = "";
        }

        $msg         = $data['msg'];
        $sign_string = $client_id . "" . $msg . "" . $client_secret;
        $sign        = md5($sign_string);
        if ($sign != $data['sign']) {
            exit();
        } else {
            $result = array("code" => 0, "msg" => "success");
            var_dump($result);
        }
        $msg = json_decode(urldecode($msg), true);

        if (strpos($data['msg'], 'WAIT_SELLER_SEND_GOODS') !== false) {
            $clapi = new ChuanglanSmsApi();
            $title = $info['response']['full_order_info']['orders'][0]['title'];
            $this->msg_model->add_card();
            
            $cardInfo = $this->msg_model->serch_card();
            if ($cardInfo) {
                $card = $cardInfo['card'];
                $pwd = $cardInfo['password'];
                $name     = $info['response']['full_order_info']['buyer_info']['fans_nickname'];
                $order_bn = $info['response']['full_order_info']['order_info']['tid'];

                $method2      = 'youzan.logistics.online.confirm'; //要调用的api名称
                $api_version2 = '3.0.0'; //要调用的api版本号
                $my_params2   = [
                    'tid'           => $order_bn,
                    'is_no_express' => '1',
                ];

                $client->post($method2, $api_version2, $my_params2, $my_files);

                //设置您要发送的内容：其中“【】”中括号为运营商签名符号，多签名内容前置添加提交
                $result = $clapi->sendSMS($phone, "【黄帝金安】您已成功订购黄帝金安{$title}，卡号：{$card}，密码：{$pwd}，请使用卡号密码登录 http://t.cn/RdALD2g 或关注【黄帝金安】公众号进行预约。");
                //$result = $clapi->sendSMS('18861855848', $phone);
                if (!is_null(json_decode($result))) {

                    $output = json_decode($result, true);
                    if (isset($output['code']) && $output['code'] == '0') {
                        echo '发送成功';
                        $this->msg_model->modify_card($name, $phone, $card, $title, $order_bn);
                    } else {
                        echo $output['errorMsg'];
                    }
                } else {
                    echo $result;
                }
            }
        }
    }

    //生成excel
    public function makeExcel()
    {
        $list = $this->msg_model->find_card();
        /** Error reporting */
        error_reporting(E_ALL);
        ini_set('display_errors', true);
        ini_set('display_startup_errors', true);
        set_time_limit(0);

        if (PHP_SAPI == 'cli') {
            die('This example should only be run from a Web Browser');
        }
        /** Include PHPExcel */
        require APPPATH . '/libraries/PHPExcel.php';
        require APPPATH . '/libraries/PHPExcel/IOFactory.php';
        $cacheMethod   = \PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
        $cacheSettings = array(
            'memoryCacheSize' => '1MB',
        );
        \PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

        // Create new PHPExcel object
        $objPHPExcel = new \PHPExcel();
        $title       = "皇帝金安" . date('Y-m-d');
        // Set document properties
        $objPHPExcel->getProperties()->setCreator("119.23.141.210:10337")
            ->setLastModifiedBy("119.23.141.210:10337")
            ->setTitle($title);
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet

        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);

        // Add some data
        $objPHPExcel->getActiveSheet()
            ->setCellValue('A1', 'NO.')
            ->setCellValue('B1', '用户名')
            ->setCellValue('C1', '手机号码')
            ->setCellValue('D1', '卡号')
            ->setCellValue('E1', '密码')
            ->setCellValue('F1', '商品名称')
            ->setCellValue('G1', '订单编号')
            ->setCellValue('H1', '时间');

        foreach ($list as $key => $value) {
            $num = $key + 2;
            $objPHPExcel->getActiveSheet()
                ->setCellValueExplicit("A{$num}", $key + 1, \PHPExcel_Cell_DataType::TYPE_STRING2)
                ->setCellValueExplicit("B{$num}", $value['name'], \PHPExcel_Cell_DataType::TYPE_STRING2)
                ->setCellValueExplicit("C{$num}", $value['phone'], \PHPExcel_Cell_DataType::TYPE_STRING2)
                ->setCellValueExplicit("D{$num}", $value['card'], \PHPExcel_Cell_DataType::TYPE_STRING2)
                ->setCellValueExplicit("E{$num}", $value['password'], \PHPExcel_Cell_DataType::TYPE_STRING2)
                ->setCellValueExplicit("F{$num}", $value['title'], \PHPExcel_Cell_DataType::TYPE_STRING2)
                ->setCellValueExplicit("G{$num}", $value['order_bn'], \PHPExcel_Cell_DataType::TYPE_STRING2)
                ->setCellValueExplicit("H{$num}", $value['create_time'], \PHPExcel_Cell_DataType::TYPE_STRING2);

            //$objPHPExcel->getActiveSheet()->getStyle("A{$num}:G{$num}")->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
            //$objPHPExcel->getActiveSheet()->getStyle("A{$num}:G{$num}")->getFill()->getStartColor()->setARGB('808080');
        }
        // Rename worksheet
        $objPHPExcel->getActiveSheet()->setTitle($title);
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(20);

        // Redirect output to a client’s web browser (Excel5)
        // header('Content-Type: application/vnd.ms-excel');
        // header('Content-Disposition: attachment;filename="' . $title . '.xls"');
        // header('Cache-Control: max-age=0');
        // // If you're serving to IE 9, then the following may be needed
        // header('Cache-Control: max-age=1');
        // // If you're serving to IE over SSL, then the following may be needed
        // header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        // header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        // header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        // header('Pragma: public'); // HTTP/1.0

        // header("Content-Type:application/force-download");

        // header("Content-Type:application/octet-stream");

        // header("Content-Type:application/download");

        // header('Content-Type:application/vnd.ms-excel');
        // header('Content-Disposition:attachment;filename="'.$title.'.xls"');
        // header('Cache-Control:max-age=0');
        $objWriter = \IOFactory::createWriter($objPHPExcel, 'Excel5');
        //$objWriter->save('php://output');

        $objWriter->save('/var/www/html/card_api/uploads/excel/' . $title . '.xls');

        $this->api_model->send_email('黄帝金安卡号和密码', 'zhangfanzhong.sh@meinian.cn', '黄帝金安', '下载excel附件', 'html', 'http://119.23.141.210:10337/uploads/excel/' . $title . '.xls');

    }

}
